package com.pfzy.ui.view.picker

import android.app.Dialog
import android.content.Context
import android.os.Build
import android.text.format.DateFormat
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Button
import android.widget.ImageView
import com.pfzy.ui.R
import com.pfzy.ui.activity.pick.DateInfo
import com.pfzy.ui.activity.pick.PickerUtils
import java.text.SimpleDateFormat
import java.util.*

class CustomDate2Picker(context: Context) {
    private var mContext: Context? = null
    private var datePickerDialog: Dialog? = null
    private var handler: ResultHandler? = null
    private var mCloseImg: ImageView? = null
    private var pvDay: Date2PickerView? = null
    private var pvHour: Date2PickerView? = null
    private var pvMinute: Date2PickerView? = null
    private var selectDay: DateInfo? = null
    private var selectHour: DateInfo? = null
    private var selectMinute: DateInfo? = null
    private var mDayList: MutableList<DateInfo> = ArrayList()
    private var mHourList: MutableList<DateInfo> = ArrayList()
    private var mMinuteList: MutableList<DateInfo> = ArrayList()
    private var mOldDayIndex = -1
    private var mOldHourIndex = -1
    private var step=5

    private fun initDialog() {
        if (datePickerDialog == null) {
            datePickerDialog = mContext?.let { Dialog(it, R.style.time_dialog) }
            // 设置是否可以使用后退键取消此对话框。
            datePickerDialog?.setCancelable(false)
            // 启用扩展窗口功能(“无标题”功能的标志，关闭屏幕顶部的标题)
            datePickerDialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
            datePickerDialog?.setContentView(R.layout.picker_date2)
            val window = datePickerDialog!!.window
            window!!.setGravity(Gravity.BOTTOM)
            // 设置在窗口边界外触摸时是否取消此对话框。如果设置为true，则对话框设置为可取消
            datePickerDialog!!.setCanceledOnTouchOutside(true)
            // 访问系统窗口管理器的窗口管理器
            val manager = mContext!!.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val dm = DisplayMetrics()
            manager.defaultDisplay.getMetrics(dm)
            window.setWindowAnimations(R.style.dialogstyle) // 添加动画
            window.setBackgroundDrawableResource(R.color.transparent)
            val lp = window.attributes
            lp.width = dm.widthPixels
            window.attributes = lp
        }
    }

    private fun initView() {
        mCloseImg = datePickerDialog!!.findViewById<View>(R.id.picker_date2_close) as ImageView
        pvDay = datePickerDialog!!.findViewById<View>(R.id.picker_date2_day) as Date2PickerView
        pvHour = datePickerDialog!!.findViewById<View>(R.id.picker_date2_hour) as Date2PickerView
        pvMinute =
            datePickerDialog!!.findViewById<View>(R.id.picker_date2_minute) as Date2PickerView
        pvDay!!.setIsLoop(false)
        pvHour!!.setIsLoop(false)
        pvMinute!!.setIsLoop(false)

        var btnSelect = datePickerDialog!!.findViewById<View>(R.id.picker_date2_submit) as Button
        btnSelect.setOnClickListener {
            if (handler != null) {
                var text = selectDay!!.text + selectHour!!.text + selectMinute!!.text
                var timeDate =
                    selectDay!!.date + " " + selectHour!!.date + ":" + selectMinute!!.date + ":" + "00"
                Log.d("时间选择", timeDate)
                var time: Long = 0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    val parse = sdf.parse(timeDate)
                    time = parse.time
                }
                handler!!.handle(text, time);
            }
            datePickerDialog!!.dismiss()
        }

        mCloseImg!!.setOnClickListener {
            datePickerDialog!!.dismiss()
        }

        addListener()
    }

    fun show2(time: Long) {
        setSelectedTime(time)
        datePickerDialog!!.show()
    }

    private fun addListener() {
        pvDay!!.setOnSelectListener(object : Date2PickerView.onSelectListener {
            override fun onSelect(index: Int, data: DateInfo) {
                Log.e("日期选择", "$index-$data")
                selectDay = data
                hourChange(index)
            }
        })
        pvHour!!.setOnSelectListener(object : Date2PickerView.onSelectListener {
            override fun onSelect(index: Int, data: DateInfo) {
                Log.e("小时选择", "$index-$data")
                selectHour = data
                minuteChange(index)
            }
        })
        pvMinute!!.setOnSelectListener(object : Date2PickerView.onSelectListener {
            override fun onSelect(index: Int, data: DateInfo) {
                Log.e("分钟选择", "$index-$data")
                selectMinute = data
            }
        })
    }

    private fun initDayTime() {
        mDayList.add(PickerUtils.getDayText(0, "今天"))
        mDayList.add(PickerUtils.getDayText(1, "明天"))
        mDayList.add(PickerUtils.getDayText(2, "后天"))
        mDayList.add(PickerUtils.getDayText(3))
        mDayList.add(PickerUtils.getDayText(4))
        mDayList.add(PickerUtils.getDayText(5))
        mDayList.add(PickerUtils.getDayText(6))
        mDayList.add(PickerUtils.getDayText(7))
        mDayList.add(PickerUtils.getDayText(8))
        mDayList.add(PickerUtils.getDayText(9))
        mDayList.add(PickerUtils.getDayText(10))
        mDayList.add(PickerUtils.getDayText(11))
        mDayList.add(PickerUtils.getDayText(12))
        mDayList.add(PickerUtils.getDayText(13))
        mDayList.add(PickerUtils.getDayText(14))
        pvDay?.setData(mDayList)
    }

    private fun setSelectedTime(time: Long) {
        initDayTime()
        _logd("选择时间:$time, 列表：$mDayList")

        for (i in 0 until mDayList.size) {
            _logd("列表：${mDayList[i].timeStart}:${mDayList[i].timeEnd}")
            if (time >= mDayList[i].timeStart && time < mDayList[i].timeEnd) {
                pvDay!!.setSelected(i)
                selectDay = mDayList[i]
                hourChange(i)
                if (i == 0) {
                    val curCalendar = Calendar.getInstance()
                    curCalendar.set(Calendar.SECOND, 0)
                    curCalendar.set(Calendar.MILLISECOND, 0)
                    var curHour = curCalendar[Calendar.HOUR_OF_DAY]
                    var curMinute = curCalendar[Calendar.MINUTE]
                    _logd("时间戳: ${curCalendar.timeInMillis}  $time")
                    if (time < curCalendar.timeInMillis) {
                        setHourList(curHour, MAX_HOUR, 0)
                        setMinuteList(curMinute, MAX_MINUTE, 0)
                    } else {
                        val timeCalendar = Calendar.getInstance()
                        timeCalendar.timeInMillis = time
                        var timeHour = timeCalendar[Calendar.HOUR_OF_DAY]
                        var timeMinute = timeCalendar[Calendar.MINUTE]

                        var hourDiff = timeHour - curHour
                        _logd("分钟差1 ：${timeHour}-${curHour}-${hourDiff}")
                        setHourList(curHour, MAX_HOUR, hourDiff)
                        if (timeHour > curHour) {
                            setMinuteList(MIN_MINUTE, MAX_MINUTE, timeMinute)
                        } else {
                            var minuteDiff = timeMinute - curMinute
                            _logd("分钟差2 ：${timeMinute}-${curMinute}-${minuteDiff}")
                            setMinuteList(curMinute, MAX_MINUTE, minuteDiff)
                        }
                    }
                } else {
                    val timeCalendar = Calendar.getInstance()
                    timeCalendar.timeInMillis = time
                    var timeHour = timeCalendar[Calendar.HOUR_OF_DAY]
                    var timeMinute = timeCalendar[Calendar.MINUTE]

                    _logd("分钟差3 ：${timeHour}-${timeMinute}")

                    setHourList(MIN_HOUR, MAX_HOUR, timeHour)
                    setMinuteList(MIN_MINUTE, MAX_MINUTE, timeMinute)
                }
                break
            }
        }
    }

    private fun hourChange(index: Int) {
        if (mOldDayIndex != index) {
            if (index == 0) {
                val calendar = Calendar.getInstance()
                _logd("时间戳: ${calendar.timeInMillis}")

                var minute = calendar[Calendar.MINUTE]
                var hour = calendar[Calendar.HOUR_OF_DAY]

                if (minute > 55) {
                    setHourList(hour + 1, MAX_HOUR, 0)
                } else {
                    setHourList(hour, MAX_HOUR, 0)

                    setMinuteList(minute, MAX_MINUTE, 0)
                }
            } else {
                if (mOldDayIndex == 0) {
                    setHourList(MIN_HOUR, MAX_HOUR, 0)
                    setMinuteList(MIN_MINUTE, MAX_MINUTE, 0)
                }
            }
            mOldDayIndex = index
        }
    }

    private fun setHourList(min: Int, max: Int, cur: Int) {
        mHourList.clear()
        for (i in min..max) {
            var date = formatTimeUnit(i)
            mHourList.add(DateInfo(date + "时", 0, 0, date))
        }
        pvHour?.setData(mHourList)
        pvHour!!.setSelected(cur)
        selectHour = mHourList[cur]
    }


    private fun setMinuteList(min: Int, max: Int, cur: Int) {
        mMinuteList.clear()
        for (i in min..max) {
            if(i%step==0){
                var date = formatTimeUnit(i)
                mMinuteList.add(DateInfo(date + "分", 0, 0, date))
            }
        }
        var curIndex = cur/step
        pvMinute?.setData(mMinuteList)
        pvMinute!!.setSelected(curIndex)
        selectMinute = mMinuteList[curIndex]
    }


    private fun minuteChange(index: Int) {
        if (mOldDayIndex == 0) {
            if (mOldHourIndex != index) {
                if (index == 0) {
                    val calendar = Calendar.getInstance()
                    _logd("时间戳: ${calendar.timeInMillis}")
                    var minute = calendar[Calendar.MINUTE]
                    setMinuteList(minute, MAX_MINUTE, 0)
                } else {
                    if (mOldDayIndex == 0) {
                        setMinuteList(MIN_MINUTE, MAX_MINUTE, 0)
                    }
                }
            }
        }
    }

    /**
     * 将“0-9”转换为“00-09”
     */
    private fun formatTimeUnit(unit: Int): String {
        return if (unit < 10) "0$unit" else unit.toString()
    }

    fun setHandler(handler: ResultHandler) {
        this.handler = handler
    }

    /**
     * 定义结果回调接口
     */
    interface ResultHandler {
        fun handle(text: String, time: Long)
    }

    init {
        this.mContext = context
        initDialog()
        initView()
    }

    companion object {
        private const val MAX_MINUTE = 59
        private const val MIN_MINUTE = 0
        private const val MAX_HOUR = 23
        private const val MIN_HOUR = 0
    }

    private fun _logd(msg: String) {
        Log.d("CustomDate2Picker", msg)
    }
}
